package com.xlz.manager;

import java.io.IOException;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import com.xlz.util.Common;
import com.xlz.worker.WorkerBeanFactory;

/**
 * 适配Spring分布式调度入口管理类.
 * @author 张蕾蕾
 * @date 2018 03 24
 */
public class DstManagerBeanFactory implements ApplicationListener<ContextRefreshedEvent>, FactoryBean<DefaultDstManager>{
	
	protected final Logger LOG = LoggerFactory.getLogger(getClass());
	
	private String appNo;
	private DataSource dataSource;
	
	@Override
	public DefaultDstManager getObject() throws Exception {
		return init();
	}

	@Override
	public Class<DefaultDstManager> getObjectType() {
		return DefaultDstManager.class;
	}

	@Override
	public boolean isSingleton() {
		return true;
	}

	public void setAppNo(String appNo) {
		this.appNo = appNo;
	}

	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}

	private DefaultDstManager init() throws IOException{
		DefaultDstManager dstManager = new DefaultDstManager();
		dstManager.getContext().setAppNo(this.appNo);
		dstManager.setDataSource(this.dataSource);
		dstManager.setContainer(Common.RUNNTIME_CONTAINER_SPRING);
		dstManager.start();
		return dstManager;
	}

	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		WorkerBeanFactory.context = event.getApplicationContext();
		event.getApplicationContext().getBean(DefaultDstManager.class);
	}

}
